package sqcon.sql;

import java.util.ArrayList;
import java.util.NoSuchElementException;
import sqcon.util.StringTokenParser;
import sqcon.util.StringParsingException;

public class SelectClause implements Clause{
	
	private static final ClauseType type = ClauseType.SELECT;
	
	private boolean distinct; //if have DISTINCT keyword
	
	private ArrayList<Attribute> attributeList;
	
	public SelectClause(){
		distinct = false;
		attributeList = new ArrayList<Attribute>();
	}
	
	public SelectClause(String clauseString) throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(clauseString);
		
		//check for the right keyword
		try{
			if(!stp.nextToken().equalsIgnoreCase(ClauseType.SELECT.toString())){
				throw new ConstructSqlException("Select Clause Parsing Error");
			}
			String nextTok = stp.nextToken();
			if(nextTok.equalsIgnoreCase("DISTINCT")){
				setDistinct(true);
				setSelectContent(stp.getRest());
			}else{
				setSelectContent(nextTok + " " + stp.getRest());
			}
		}catch(StringParsingException e){
			throw new ConstructSqlException("Select Clause Parsing Error");
		}catch(NoSuchElementException nsee){
			throw new ConstructSqlException("Select Clause Parsing Error");
		}
	}
	
	public ClauseType getClauseType(){
		return type;
	}
	
	public void setDistinct(boolean distinct){
		this.distinct = distinct;
	}
	
	public boolean isDistinct(){
		return distinct;
	}
	
	public void addAttribute(Attribute attr){
		attributeList.add(attr);
	}
	
	public ArrayList<Attribute> getAttributeList(){
		return attributeList;
	}
	
	public String printString(){
		String ret = "SELECT";
		if(distinct){
			ret = ret + " DISTINCT";
		}
		
		String attrListStr = "";
		for(Attribute attr : attributeList){
			attrListStr = attrListStr + ", " + attr.toString();
		}

		return ret + " " + attrListStr.substring(2);
	}
	
	public String toString(){
		return printString();
	}
	
	private void setSelectContent(String str) throws ConstructSqlException{
		StringTokenParser stp = new StringTokenParser(str, ",");
		try{
			while(stp.hasMoreTokens()){
				attributeList.add(Attribute.generateAttribute(stp.nextToken()));
			}
		}catch(StringParsingException e){
			throw new ConstructSqlException("Select Clause Parsing Error");
		}
	}
}
